/*
 * Copyright (c) 2015. 石头哥哥
 */

package com.comom.manager.kit.ehcache;

import com.mengchong.server.model.dbsql.modelVo.Msg;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 石头哥哥
 *         </P>
 *         Date:   2015/5/28
 *         </P>
 *         Time:   10:51
 *         </P>
 *         Package: dcServer-parent
 *         </P>
 *         <p/>
 *         注解：    ehcachemanager
 *         spring inject ehcachemanager ,defalut is singleton
 */
@Service
public class EhcacheManager {

    /**
     * cache manager in ehcache
     * singleton CacheManager
     */
    private final CacheManager cacheManager;

    public void setEhcaheXML(String ehcaheXML) {
        this.ehcaheXML = ehcaheXML;
    }

    /**
     * ehcache config
     */
    private String ehcaheXML = "/WEB-INF/res/ehcache.xml";


    /**
     *
     */
    @SuppressWarnings({"RedundantStringToString", "ConstantConditions"})
    private EhcacheManager() {
        String osName = System.getProperties().getProperty("os.name"); //操作系统名称
        if (osName.equals("Mac")){
            //mac os
            ehcaheXML  =this.getClass().getClassLoader().getResource("").getPath().toString().replace("WEB-INF/classes/","WEB-INF/res/ehcache.xml");
        }else {//windows
            ehcaheXML = this.getClass().getClassLoader().getResource("").getPath().toString().replace("classes/", "res/ehcache.xml");

        }

        this.cacheManager = new CacheManager(ehcaheXML);
    }


    /**
     * @param ehcaheXML
     */
//    private EhcacheManager(String ehcaheXML) {
//        this.ehcaheXML = ehcaheXML;
//        this.cacheManager = new CacheManager(ehcaheXML);
//    }




    /**
     * cacheName 查找出cache name中 所有对象
     *
     * @param cacheName
     * @return
     */
    public ArrayList<Object> getList(String cacheName) {
        try {
            Cache cache = this.cacheManager.getCache(cacheName);
            if (cache == null) {
                throw new RuntimeException("please check ehcache.xml,there's not " +
                        cacheName + " cache partition or remove it?!");
            }
            Collection<Element> elementCollection = cache.getAll(cache.getKeys()).values();
            if (elementCollection.size() != 0) {
                ArrayList<Object> objectArrayList = new ArrayList<Object>();       // temp  cache
                for (Element element : elementCollection) {
                    objectArrayList.add(element.getObjectValue());  //
                }
                return objectArrayList;
            }
        } catch (NullPointerException e) {
            return null;                   //
        }
        return null;
    }


    /**
     * 定制方法了 （ps 有点入侵了哈）
     * 移除 缓存中的msg
     *
     * @param cacheName
     * @param uid       待移除标志类型
     */
    public void removeMsgByUid(String cacheName, int uid) {
        try {
            Cache cache = this.cacheManager.getCache(cacheName);
            if (cache == null) {
                throw new RuntimeException("please check ehcache.xml,there's not " +
                        cacheName + " cache partition or remove it?!");
            }
            Collection<Element> elementCollection = cache.getAll(cache.getKeys()).values();
            if (elementCollection.size() != 0) {
                for (Element element : elementCollection) {
                    Msg msg = (Msg) element.getObjectValue();
                    if (msg.getTouid() == uid) cache.remove(element.getObjectKey()); // remove object by key
                }
                elementCollection.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    @PostConstruct
//    public void removeMsgByUidTest() {
//        Msg msg = new Msg();
//        msg.setTouid(1);
//        Msg msg1=new Msg();
//        msg1.setTouid(3);
//        put(CacheConstants.msg, 1, msg);
//        put(CacheConstants.msg, 2, msg1);
//        Msg o = (Msg) get(CacheConstants.msg, 1);
//        removeMsgByUid(CacheConstants.msg, 1);
//        System.out.println("try again get msg.....");
//        o = (Msg) get(CacheConstants.msg, 1);
//        if (o == null) {
//            Msg o2= (Msg) get(CacheConstants.msg,2);
//            System.out.println("msg object had removed.....");
//        }
//
//    }


    /**
     * @param cacheName
     * @param key
     * @return
     */
    public Object get(String cacheName, final Object key) {
        try {
            Cache cache = this.cacheManager.getCache(cacheName);
            if (cache == null) {
                throw new RuntimeException("please check ehcache.xml,there's not " +
                        cacheName + " cache partition or remove it?!");
            }
            return cache.get(key).getObjectValue();
        } catch (NullPointerException e) {
            return null;                   //
        }
    }

    /**
     * @param cacheName
     * @param key
     * @param value
     */
    public void update(String cacheName, final Object key, final Object value) {
        this.put(cacheName, key, value);
    }

    /**
     * @param cacheName
     * @param key
     * @param value
     */
    public void put(String cacheName, final Object key, final Object value) {
        Cache cache = this.cacheManager.getCache(cacheName);
        if (cache == null) {
            throw new RuntimeException("please check ehcache.xml,there's not " +
                    cacheName + " cache partition");
        }
        cache.put(new Element(key, value));
    }

    /**
     * remove key-value
     *
     * @param cacheName
     * @param key
     */
    public void remove(String cacheName, final Object key) {
        Cache cache = this.cacheManager.getCache(cacheName);
        if (cache == null) {
            throw new RuntimeException("please check ehcache.xml,there's not " +
                    cacheName + " cache partition");
        }
        cache.remove(key);
    }


    /**
     * Removes all cached items.
     *
     * @param cacheName
     */
    public void clear(String cacheName) {
        Cache cache = this.cacheManager.getCache(cacheName);
        if (cache == null) {
            throw new RuntimeException("please check ehcache.xml,there's not " +
                    cacheName + " cache partition");
        }
        cache.removeAll();
    }


    /**
     * remove   cacheName partition
     *
     * @param cacheName
     */
    public void removeCache(String cacheName) {
        this.cacheManager.removeCache(cacheName);
    }





}
